<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/18
 * Time: 19:20
 */

namespace api\flower\controller;
use think\Controller;
use wxpay\database\WxPayUnifiedOrder;
use wxpay\JsApiPay;
use wxpay\WxPayApi;
use wxpay\WxPayConfig;
use think\Db;
use think\Session;
use wxpay\PayNotifyCallBack;
use wxpay\database\WxPayDataBase;
use wxpay\database\WxPayResults;
use wxpay\NativePay;
//import('wxpay\JsApiPay');
class WeixinPayController extends Controller
{
    public function wxpay(){
        try{
            $baoyuname = urldecode(input('baoyuename'));
            $price = urldecode(input('price'));
            $choose = urldecode(input('time'));
            $address = urldecode(input('address'));
            $tlength = urldecode(input('tlength'));
            Session::set('orderprice',$price);
            // $price = round($price,2);
            //①、获取用户openid
            $tools = new JsApiPay();
            /*$tools = new JsApiPay();
            $openId = $tools->GetOpenid();*/
            $openId = Session::get('openid');

            $result = Db::name('flower_userinfo')->where('openid',$openId)->find();
            $phone = $result['phone'];
            //$integral = $result['integral'];
            //②、统一下单
            $input = new WxPayUnifiedOrder();
            $input->SetBody('flowerstory');
            $input->SetAttach("flowerstory");
            $wexinordernum = WxPayConfig::MCHID.date("YmdHis");

            //$input->setOutTradeNo(WxPayConfig::MCHID.date("YmdHis"));//商户订单号
            $input->setOutTradeNo($wexinordernum);//商户订单号
            $input->setTotalFee($price*100);
            // $input->setTotalFee(1);
            $input->setTimeStart(date("YmdHis"));
            $input->setTimeExpire(date("YmdHis", time() + 600));
            $input->setGoodsTag("flowerstory");
            $httpurl = 'http://'.$_SERVER['HTTP_HOST'];
            $input->setNotifyUrl($httpurl."/api/flower/weixin_pay/notify");
            $input->setTradeType("JSAPI");
            $input->setOpenid($openId);

            $order = WxPayApi::unifiedOrder($input);

            //=====================将订单信息存入到数据库中 start==================
            $data['order'] = $wexinordernum;
            $data['weixinorders'] = $wexinordernum;
            $data['userid'] = $openId;
            $data['stime'] = time();
            $data['content'] = $baoyuname.' /'.$choose.' /价格'.$price.'元';
            $content =  $baoyuname.' /'.$choose.' /价格'.$price.'元'.'<br/>'.$address;
            $data['address'] = $address;
            $data['status'] = 1;
            $data['price'] = $price;
            $data['phone'] = $phone;
            //echo strtotime('+'.$tlength.' month').$tlength;exit;
            $data['endtime'] = strtotime('+'.$tlength.' month');
            $result = Db::name('flower_orders')->insert($data);
            //$datas['integral']=$integral+$price;
            // $result2 = Db::name('flower_userinfo')->where('openid',$openId)->update($datas);
            //=====================将订单信息存入到数据库中 end==================
            // echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            // print_r($order);
            $jsApiParameters = $tools->GetJsApiParameters($order);
            // print_r($jsApiParameters).'<br/>';
//获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();

            $htmlcontent = "<script type='text/javascript'> function jsApiCall(){

          WeixinJSBridge.invoke('getBrandWCPayRequest',".$jsApiParameters. ",
          function(res){
           WeixinJSBridge.log(res.err_msg);
//alert(res.err_code+res.err_desc+res.err_msg);
          window.location.href='http://pay.yzztnet.com/flowers/default.html';
        });}";
            $htmlcontent = $htmlcontent."function callpay(){

          if (typeof WeixinJSBridge == 'undefined'){
          if( document.addEventListener ){
          document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	</script>";

            $htmlcontent = $htmlcontent."	<script type=\"text/javascript\">
	//获取共享地址
	function editAddress()
	{
		WeixinJSBridge.invoke(
			'editAddress',
			".$editAddress.",
			function(res){
				var value1 = res.proviceFirstStageName;
				var value2 = res.addressCitySecondStageName;
				var value3 = res.addressCountiesThirdStageName;
				var value4 = res.addressDetailInfo;
				var tel = res.telNumber;

				//alert(value1 + value2 + value3 + value4 + \":\" + tel);
			}
		);
	}

	window.onload = function(){
		if (typeof WeixinJSBridge == 'undefined'){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', editAddress);
		        document.attachEvent('onWeixinJSBridgeReady', editAddress);
		    }
		}else{
			editAddress();
		}
	};

	</script>
</head>";
            $htmlcontent1='<!doctype html>'.
                '<html lang="en">'.
                '<head>'.
                '    <meta charset="UTF-8">'.
                '    <meta name="viewport"'.
                '          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">'.
                '    <meta http-equiv="X-UA-Compatible" content="ie=edge">'.
                '    <title>微信支付详情页</title>'.
                '    <style>'.
                '        *{'.
                '            margin: 0;'.
                '            padding: 0;'.
                '        }'.
                '        body{'.
                '            width: 100vw;'.
                '            height: 100vh;'.
                '            position: relative;'.
                '            background-color:#f0f0f0 ;'.
                '            overflow: hidden;'.
                '        }'.
                '        .back{'.
                '            position: absolute;'.
                '            top:0;'.
                '            left:0;'.
                '            width: 100%;'.
                '            height: 35%;'.
                '        }'.
                '        .back >img{'.
                '            width: 100%;'.
                '            height: 100%;'.
                '        }'.
                '        .order{'.
                '            position: absolute;'.
                '            top:35%;'.
                '            left:0;'.
                '            width: 100%;'.
                '            height: 18%;'.
                '            background-color: white;'.
                '        }'.
                '        .order>div{'.
                '            width: 100%;'.
                '            font-size: .8rem;'.
                '            padding-left: 1.2rem;'.
                '        }'.
                '        .order>div:nth-child(1){'.
                '            padding-top: 4%;'.
                '        }'.
                '        .order>div:nth-child(2){'.
                '            padding-top: 1.5%;'.
                '            padding-bottom: 1.5%;'.
                '        }'.
                '        .grey{'.
                '            color: #545151;'.
                '        }'.
                '        .money{'.
                '            position: absolute;'.
                '            top: 53.2%;'.
                '            left: 0;'.
                '            width: 100%;'.
                '            height: 14.5%;'.
                '            background-color: white;'.
                '        }'.
                '        .money>div{'.
                '            height: 6rem;'.
                '            line-height: 6rem;'.
                '            padding-left: 1.2rem;'.
                '        }'.
                '        .money>div>span{'.
                '            padding-left: .5rem;'.
                '            color:#fe5478;'.
                '            font-size: 1.2rem;'.
                '        }'.
                '        .submit{'.
                '            position: absolute;'.
                '            left:0;'.
                '            width: 100%;'.
                '            height: 30.5%;'.
                '            bottom: 0;'.
                '            background-color: white;'.
                '        }'.
                '        .submit>div{'.
                '            height: 8rem;'.
                '            line-height: 8rem;'.
                '            padding-left: 7rem;'.
                '            position: relative;'.
                '        }'.
                '        .submit>div>img{'.
                '            width: 2rem;'.
                '            height: 2rem;'.
                '        }'.
                '        .submit>div>span{'.
                '            font-size: 1.5rem;'.
                '            display: block;'.
                '            position: absolute;'.
                '            bottom: .6rem;'.
                '            right: 6.5rem;'.
                '        }'.
                '        .submit>button{'.
                '            width: 85%;'.
                '            height: 2.5rem;'.
                '            text-align: center;'.
                '            line-height: 2.5rem;'.
                '            border-radius: .2rem;'.
                '            background: #fe5478;'.
                '            color: #ffffff;'.
                '            position: absolute;'.
                '            bottom: 3rem;'.
                '            left: 7.5%;'.
                '            font-weight: bold;'.
                '            border: none;'.
                '        }'.
                '    </style>'.$htmlcontent.
                '<body>'.
                '    <div class="back">'.
                '        <img src="'.$httpurl.'/flowers/Images/back.jpg" alt="">'.
                '    </div>'.
                '    <div class="order">'.
                '        <div>订单已生成,待支付</div>'.
                '        <div class="grey">订单号:'.$wexinordernum.'</div>'.
                '        <div class="grey" >订单详情:'.$content.'</div>'.
                '        <div class="grey">订单价格:'.$price.'元钱</div>'.
                '    </div>'.
                '    <div class="money">'.
                '        <div>您总共需支付:<span>￥</span><span>'.$price.'</span></div>'.
                '    </div>'.
                '    <div class="submit">'.
                '        <div>'.
                '            <img src="'.$httpurl.'/flowers/Images/wechat.png"alt="">'.
                '            <span>微信支付</span>'.
                '        </div>'.
                '        <button onclick=\'callpay()\' >微信支付</button>'.
                '    </div>'.
                '</body>'.
                '</html>';

            echo htmlspecialchars_decode(htmlspecialchars($htmlcontent1));
        }catch(Exception $ex){
            echo $ex->getMessage();
        }

    }

    /**
     * 微信回调函数
     */
    public function notify(){

        // 测试
        $weixinData = file_get_contents("php://input");

        try {
            $resultObj = new WxPayResults();
            $weixinData = $resultObj->Init($weixinData);

        } catch(\Exception $e) {
            $resultObj->setData('return_code', 'FAIL');
            $resultObj->setData('return_msg', $e->getMessage());
            return $resultObj->toXml();
        }
        if($weixinData['return_code'] === 'FAIL' || $weixinData['result_code'] !== 'SUCCESS') {
            $resultObj->setData('return_code', 'FAIL');
            $resultObj->setData('return_msg', 'error');
            return $resultObj->toXml();
        }
        //根据out_trade_to来查询订单数据
        $outTradeTo = $weixinData['out_trade_no'];
        file_put_contents('tmp/2.txt',$weixinData['out_trade_no'], FILE_APPEND);
        $order =  Db::name('flower_orders')->where('weixinorders',$outTradeTo)->find();

        if(!$order || $order['status'] == 2) {
            $resultObj->setData('return_code', 'SUCCESS');
            $resultObj->setData('return_msg', 'OK');
            return $resultObj->toXml();
        }
        //更新表 订单表  商品表

        try {

            Db::name('flower_orders')->where('weixinorders',$outTradeTo)->update(array('paytime'=>time(),'status'=>'2'));//修改订单支付的时间以及订单状态
            $sql = Db::name('flower_orders')->getLastSql();

            //=====用户支付的金额都要增加在积分中去start=====
            $orderprice=Session::get('orderprice');
            $openid = Session::get('openid');
            // $openid='oCG5CxMLFva7ei2s_a0G2NrbENac';
            $result = Db::name('flower_userinfo')->where('openid',$openid)->find();
            $integral = $result['integral']+round($orderprice);
            Db::name('flower_userinfo')->where('openid',$openid)->update(array('integral'=>$integral));
            //=====用户支付的金额都要增加在积分中去end=====
            // 发送邮件 给用户
        } catch (\Exception $e) {
            // 说明 没有更新  告诉微信 服务器 我们还需要 回调
            return false;
        }
        $resultObj->setData('return_code', 'SUCCESS');
        $resultObj->setData('return_msg', 'OK');
        return $resultObj->toXml();
    }
}